import { fakeAccountLogin } from '@/services/login';
import type { Effect, Reducer } from 'umi';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';
import { history } from 'umi';
import { stringify } from 'querystring';

export type StateType = {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin'
}

export type ModelType = {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  }
  reducers: {
    changeLoginStatus: Reducer<StateType>
  }
}

const Model: ModelType = {
  namespace: 'login',

  state: {
    status: undefined
  },

  effects: {
    *login({ payload }, { call, put }) {
        const response = yield call(fakeAccountLogin, payload);
        yield put({
          type: 'changeLoginStatus',
          payload: response
        })
        // 成功
        if(response.status === 'ok') {
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          message.success('🎉 🎉 🎉  登录成功！');
          let{ redirect } = params as { redirect: string }
          if(redirect) {
            const redirectUrlParams = new URL(redirect);
            if(redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if(redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              window.location.href = '/';
              return;
            }
          }
          history.replace(redirect || '/manage');
        }
    },
    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      if(window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href
          })
        })
      }
    }
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      console.log(payload.status);
      return {
        ...state,
        status: payload.status,
        type: payload.type
      }
    }
  }
}

export default Model;